﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.ModelBinding;
using RMS.Models;
using RMS.Models.DatabaseManager;
using RMS.Models.Repository;

namespace RMS.Pages
{
    public partial class UserAccount : System.Web.UI.Page
    {
        UserManager manager = new UserManager();
        Repository repo = new Repository();

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        public IEnumerable<User> GetUserInformation()
        {
            if (Session["ID"] == null)
            {
                Response.Redirect("~/Pages/Login.aspx");
            }
            int userID = (int)Session["ID"];
            return manager.AllUsers.Where(u => u.Us_ID == userID);
        }

        public void UpdateUser(int Us_Id)
        {
            User user = manager.GetUser(Us_Id);
            IValueProvider provider = new FormValueProvider(ModelBindingExecutionContext);
            
            if (ModelState.IsValid)
            {
                if (user != null && TryUpdateModel<User>(user, provider))
                    manager.UpdateUser(user);
            }
        }

        public List<Retreat> GetUserReservations()
        {
            int userID = (int)Session["ID"];
            List<Retreat> retreats = new List<Retreat>();
            
            IEnumerable<Reservation> userReservations = repo.Reservations.Where(i => i.Res_UsID == userID);

            foreach (Reservation r in userReservations)
            {
                Retreat retreat = repo.GetRetreat(r.Res_RetID);
                
                retreats.Add(retreat);
            }

            return retreats;
        
        }

        public void DeleteReservation(int Ret_ID)
        {
            int userID = (int)Session["ID"];

            Reservation res = repo.Reservations.Where(r => r.Res_RetID == Ret_ID && r.Res_UsID == userID).FirstOrDefault();

            if (res != null)
            {
                repo.DeleteReservation(res);
            }
        }

        public string getChosenRetreatDate(int Ret_ID)
        {
            string str = "";
            int userID = (int)Session["ID"];
            Reservation res = repo.Reservations.Where(r => r.Res_RetID == Ret_ID && r.Res_UsID == userID).FirstOrDefault();
            str += res.Res_Chosen_Date;

            return str;
        }

        protected void btnChangePass_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/ChangePassword.aspx");
        }

        protected void btnViewVolunteering_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/Volunteer.aspx");
        }
    }
}